package com.lei.app.server.impl;

import com.lei.app.dto.SocketRoomDTO;
import com.lei.app.dto.SocketRoomUserDTO;
import com.lei.app.entity.socket.room.SocketRoom;
import com.lei.app.server.ISocketRoomService;
import com.lei.app.server.ISocketRoomUserService;
import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Dao;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author 郑兴泉 956607644@qq.com
 * @data 2020/4/13
 * 描述：
 */
@IocBean(args = {"refer:dao"})
@Slf4j
public class SocketRoomServiceImpl extends BaseServiceImpl<SocketRoom> implements ISocketRoomService {
    public SocketRoomServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private ISocketRoomUserService socketRoomUserService;

    @Override
    public List<SocketRoomDTO> findAll() {
        // 所有房间
        List<SocketRoom> socketRooms =  query(getWhere());
        for (SocketRoom socketRoom : socketRooms) {
            // 房间下面的所有人员
            socketRoom.setUsers(socketRoomUserService.query(socketRoomUserService.getWhere()
                    .and(new Static(" uuid IN (SELECT userId FROM `web_socket_room_user` WHERE roomId = '"+socketRoom.getUuid()+"')"))));
        }

        List<SocketRoomDTO> rooms = new ArrayList<>(socketRooms.size());
        socketRooms.forEach(socketRoom -> {
            SocketRoomDTO roomDTO = SocketRoomDTO.builder()
                        .name(socketRoom.getName())
                        .uuid(socketRoom.getUuid())
                    .build();
            if(Objects.nonNull(roomDTO.getUser()) && !roomDTO.getUser().isEmpty()){
                List<SocketRoomUserDTO> roomUsers = new ArrayList<>(10);
                roomDTO.getUser().forEach(user -> {
                    SocketRoomUserDTO roomUserDTO = SocketRoomUserDTO.builder()
                            .name(user.getName())
                            .uuid(user.getUuid())
                            .build();
                    roomUsers.add(roomUserDTO);
                });
                roomDTO.setUser(roomUsers);
            }
            rooms.add(roomDTO);
        });
        return rooms;
    }
}
